package com.artezio.testapp.service.ajax;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.artezio.testapp.dao.CityDAO;
import com.artezio.testapp.domain.City;
import com.artezio.testapp.domain.ajax.DataTablesParamModel;
import com.google.gson.JsonArray;
import com.google.gson.JsonPrimitive;

@Service
public class DataTablesCityService {
	
    @Autowired
    private CityDAO cityDAO;
	
    
    @Transactional
    public List<City> listCity(DataTablesParamModel param) {
    	return cityDAO.listCity(param);
    }
    

	public static List<City> order(DataTablesParamModel param, List<City> cityList){
		
		List<City> resultList = new ArrayList<City>(cityList);
		
		final int sortColumnIndex = param.iSortColumnIndex;
		final int sortDirection = param.sSortDirection.equals("asc") ? 1 : -1;
		
		Collections.sort(resultList, new Comparator<City>(){
			public int compare(City c1, City c2) {	
				switch(sortColumnIndex){
					case 0:
						return c1.getId().compareTo(c2.getId()) * sortDirection;
					case 1:
						return c1.getName().compareTo(c2.getName()) * sortDirection;
					case 2:
						return c1.getPopulation().compareTo(c2.getPopulation()) * sortDirection;
				}
				return 0;
			}
		});
		
		return resultList;
	}
	
	
	public static List<City> paginate(DataTablesParamModel param, List<City> cityList){
		
		List<City> resultList = new ArrayList<City>(cityList);
		
		if(cityList.size()< param.iDisplayStart + param.iDisplayLength) {
			resultList = cityList.subList(param.iDisplayStart, cityList.size());
		} else {
			resultList = cityList.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength);
		}
		
		return resultList;
	}
	
	
	public static List<City> filter(DataTablesParamModel param, List<City> cityList){
		
		List<City> resultList = new ArrayList<City>();
		
		for(City city : cityList){
			if(	city.getName().toLowerCase().contains(param.sSearch.toLowerCase())){
				resultList.add(city);
			}
		}
		
		return resultList;
	}
	
	
	public static JsonArray generateJsonArray(List<City> cityList){
		
		JsonArray data = new JsonArray();
		
		for(City city : cityList){
			JsonArray row = new JsonArray();
			row.add(new JsonPrimitive(city.getId()));
			row.add(new JsonPrimitive(city.getName()));
			row.add(new JsonPrimitive(city.getPopulation()));
			data.add(row);
		}
		
		return data;
	
	}
}
